import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  NavBar,
  Grid,
  Image,
  Card,
  Empty,
  InfiniteScroll,
  DotLoading,
  Toast,
  SwipeAction,
  Dialog
} from 'antd-mobile';
import { getProductPlaceholder } from '../../utils/imageUtils';
import { getFavorites, removeFavorite } from '../../api/store';
import './Favorites.css';

const Favorites = () => {
  const navigate = useNavigate();
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(false);

  // 获取收藏列表
  const fetchFavorites = useCallback(async () => {
    setLoading(true);
    try {
      const favoriteProducts = await getFavorites();
      console.log('获取收藏列表:', favoriteProducts);
      
      // 确保返回的是数组
      const safeProducts = Array.isArray(favoriteProducts) ? favoriteProducts : [];
      setProducts(safeProducts);
      
      if (safeProducts.length === 0) {
        Toast.show({
          content: '暂无收藏商品',
          position: 'bottom',
        });
      }
    } catch (error) {
      console.error('获取收藏列表失败:', error);
      Toast.show({
        icon: 'fail',
        content: '获取收藏列表失败',
      });
      setProducts([]);
    } finally {
      setLoading(false);
      setHasMore(false);
    }
  }, []);

  // 首次加载
  useEffect(() => {
    fetchFavorites();
  }, [fetchFavorites]);

  // 返回上一页
  const back = () => {
    navigate(-1);
  };

  // 跳转到商品详情
  const goToProductDetail = (productId) => {
    navigate(`/product/${productId}`);
  };

  // 取消收藏
  const handleRemoveFavorite = async (productId) => {
    try {
      const result = await removeFavorite({ productId });
      if (result.success) {
        Toast.show({
          icon: 'success',
          content: '已取消收藏',
        });
        // 更新列表
        setProducts(products.filter(product => product.id !== productId));
      } else {
        Toast.show({
          content: result.message || '操作失败',
        });
      }
    } catch (error) {
      console.error('取消收藏失败:', error);
      Toast.show({
        icon: 'fail',
        content: '操作失败，请重试',
      });
    }
  };

  // 确认取消收藏
  const confirmRemoveFavorite = (productId, productName) => {
    Dialog.confirm({
      content: `确定取消收藏"${productName}"吗？`,
      onConfirm: () => {
        handleRemoveFavorite(productId);
      },
    });
  };

  // 加载更多数据（这里不需要实际加载更多，因为一次性获取所有收藏）
  const loadMore = async () => {
    return;
  };

  // 确保products是数组
  const safeProducts = Array.isArray(products) ? products : [];

  return (
    <div className="favorites-page">
      <NavBar onBack={back}>我的收藏</NavBar>

      <div className="favorites-result">
        {safeProducts.length === 0 && !loading ? (
          <Empty description="暂无收藏商品" />
        ) : (
          <Grid columns={2} gap={8}>
            {safeProducts.map(product => (
              <Grid.Item key={product.id}>
                <SwipeAction
                  rightActions={[
                    {
                      key: 'delete',
                      text: '取消收藏',
                      color: 'danger',
                      onClick: () => confirmRemoveFavorite(product.id, product.name)
                    }
                  ]}
                >
                  <Card
                    className="product-card"
                    onClick={() => goToProductDetail(product.id)}
                  >
                    <Image src={product.images?.[0] || product.image || getProductPlaceholder(product.name)} fit='cover' />
                    <div className="product-info">
                      <div className="product-name">{product.name}</div>
                      <div className="product-price">
                        <span className="price">¥{product.price.toFixed(2)}</span>
                        {product.originalPrice && (
                          <span className="original-price">¥{product.originalPrice.toFixed(2)}</span>
                        )}
                      </div>
                      <div className="product-sales">已售 {product.sales}</div>
                    </div>
                  </Card>
                </SwipeAction>
              </Grid.Item>
            ))}
          </Grid>
        )}

        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
          {hasMore ? (
            <div className="loading-more">
              <span>加载中</span>
              <DotLoading />
            </div>
          ) : (
            safeProducts.length > 0 && <div className="loading-complete">没有更多了</div>
          )}
        </InfiniteScroll>
      </div>
    </div>
  );
};

export default Favorites; 